package boddaert.philippe.cashGame.parser.page;

import java.util.ArrayList;
import java.util.List;

import au.id.jericho.lib.html.Element;
import boddaert.philippe.cashGame.Game;
import boddaert.philippe.cashGame.site.ParsedPage;
import boddaert.philippe.cashGame.site.WebGame;
import boddaert.philippe.cashGame.site.WebPage;

/**
 * A Web Page parser
 * 
 * @author obiwan
 * 
 */
public abstract class WebPageParser implements IWebPageParser {

	public final ParsedPage parse(WebPage page) throws Exception {
		if (page == null)
			throw new IllegalArgumentException();
		List<Game> games = new ArrayList<Game>();

		List<WebGame> gamesList = extractGamesList(page);

		if (gamesList != null)
			games = parseGameList(gamesList);

		return constructAParsedPage(games);
	}

	private List<Game> parseGameList(List<WebGame> gamesList) {
		if (gamesList == null)
			return null;

		List<Game> games = new ArrayList<Game>();
		for (WebGame webGame : gamesList)
			games.add(getGameParser().parse(webGame));
		return games;

	}

	private ParsedPage constructAParsedPage(List<Game> games) {
		ParsedPage parsedPage = new ParsedPage();

		if (games != null) {
			for (Game game : games) {
				parsedPage.addGame(game);
			}
		}
		return parsedPage;
	}

	/**
	 * Extract a list of WebGame representation from a WebPage
	 * 
	 * @param page
	 *            : web page
	 * 
	 * @return a list of WebGame representation from a WebPage, null if there is
	 *         no game to extract
	 */
	protected abstract List<WebGame> extractGamesList(WebPage page);

}
